"use client";

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { webAPI } from '@/lib/api';
import type { Product } from '@/lib/api';

interface RecommendedProductsProps {
  pageSize?: number;
  title?: string;
  showMoreLink?: boolean;
}

export default function RecommendedProducts({ pageSize = 10, title = '推荐产品', showMoreLink = true }: RecommendedProductsProps) {
  const [products, setProducts] = useState<Product[]>([]);

  useEffect(() => {
    (async () => {
      try {
        const res = await webAPI.getRecommendProducts(pageSize);
        if (res.success) {
          setProducts(res.data || []);
        } else {
          setProducts([]);
        }
      } catch (e) {
        console.error('获取推荐产品失败:', e);
        setProducts([]);
      }
    })();
  }, [pageSize]);

  return (
    <div className="bg-white rounded-xl shadow-md p-6">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-xl font-bold text-slate-800">{title}</h2>
        {showMoreLink && (
          <Link href="/products" className="text-blue-600 hover:text-blue-700 font-medium" style={{fontSize: '16px'}}>
            查看更多 →
          </Link>
        )}
      </div>
      {products.length > 0 ? (
        <div className="space-y-4">
          {products.map(product => (
            <div key={product.id} className="border-b border-slate-100 pb-4 last:border-b-0">
              <div className="flex items-center gap-3">
                {product.coverImage && (
                  <img src={product.coverImage} alt={product.title} className="w-16 h-12 object-contain rounded bg-white flex-shrink-0" />
                )}
                <div className="min-w-0">
                  <Link 
                    href={`/products/${product.slug}`} 
                    className="font-semibold !text-black hover:!text-gray-800 line-clamp-2"
                  >
                    {product.title}
                  </Link>
                  <p className="text-xs text-slate-500 mt-1 line-clamp-2">
                    {product.summary}
                  </p>
                  <p className="text-xs text-slate-500 mt-1 line-clamp-2">
                    {product.developerNickname || product.author}
                  </p>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-4">
          <p className="text-slate-500">暂无产品</p>
        </div>
      )}
    </div>
  );
}


